package com.viewpagertext.fragments;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.viewpagertext.DBHelper.AppDatabase;
import com.viewpagertext.DBHelper.Dao.SearchHistoryDao;
import com.viewpagertext.DBHelper.Dao.StarredSongDao;
import com.viewpagertext.R;
import com.viewpagertext.activitys.PlayActivity;
import com.viewpagertext.adapters.BannerViewHolder;
import com.viewpagertext.adapters.MusicGridAdapter;
import com.viewpagertext.constructor.MessageEvent;
import com.viewpagertext.constructor.SongsDatas;
import com.viewpagertext.json.HotSongs;
import com.viewpagertext.json.StarredSong;
import com.viewpagertext.utils.HttpUtil;
import com.viewpagertext.views.GridSpaceitemDecoration;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import static com.viewpagertext.adapters.MusicGridAdapter.FindImgUrlPath;
import static com.viewpagertext.adapters.MusicGridAdapter.FindSongsId;
import static com.viewpagertext.adapters.MusicGridAdapter.MyStarredSong;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Response;

public class FindFragment extends Fragment {
    StarredSongDao helper = AppDatabase.getInstance().starredSongDao();
    int curState;
    private static final int STATE_INIT = 0;

    private static final int STATE_REFRESH = 1;

    private static final int STATE_LOAD_MORE = 2;
    private MZBannerView mzBanner;
    private RecyclerView rv_Grid;
    private MusicGridAdapter musicGridAdapter;
    private ArrayList<SongsDatas> mDatas = new ArrayList<>();
    private ArrayList<SongsDatas> mDatas2 = new ArrayList<>();
    private View view;
    Long min = 2180863776L; // 定义范围的最小值
    Long max = 2983863776L; // 定义范围的最大值
    private String findsongs = "https://api.injahow.cn/meting/?type=playlist&id=";


    // 获取LinearLayout实例
    LinearLayout linearLayoutHotSong;
    LinearLayout linearLayoutNewSong;
    LinearLayout linearLayoutMySong;
    SongsDatas ssHot;
    SongsDatas ssNew;
    MaterialRefreshLayout refreshLayout;
    private int[] RES = {R.mipmap.banner1, R.mipmap.banner2, R.mipmap.banner3, R.mipmap.banner4, R.mipmap.banner5, R.mipmap.banner6};

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_find, container, false);

        initBanner(view);//Banner
        initRvGird(view);//RecyclerViewGrid
        sendRequestWithOkHttp();
        return view;
    }

    public void initBanner(View view) {

        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < RES.length; i++) {
            list.add(RES[i]);
        }

        mzBanner = view.findViewById(R.id.banner);
        linearLayoutHotSong = view.findViewById(R.id.HotSong);

        // 设置点击监听器

        linearLayoutHotSong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 这里写您的点击事件处理代码
                String list = findsongs + "3778678";
                HttpUtil.sendOkHttpRequest(list, new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        ranage[0]++;
                        // Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String responseData = response.body().string();//得到服务器返回的具体内容
                        Log.d("MainActivity", "测试结果" + responseData);
                        if (responseData.startsWith("{")) {
                            Send();
                        } else {
                            count++;
                            parseJSONWithGSON(responseData, 3778678L);

                            Intent intent = new Intent(getActivity(), PlayActivity.class);
                            FindImgUrlPath = ssHot.getImageurl();//获取图片地址设置全局供ListFragment接收
                            FindSongsId = ssHot.getId();//获取FindFragment歌单ID

                            String ft = "热歌榜";
                            EventBus.getDefault().postSticky(new MessageEvent(ft));//发送
                            getActivity().startActivity(intent);
//                            }
                        }

                    }
                });
            }
        });

        //新歌榜
        linearLayoutNewSong = view.findViewById(R.id.NewSong);

        // 设置点击监听器
        linearLayoutNewSong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 这里写您的点击事件处理代码
                String list = findsongs + "19723756";
                HttpUtil.sendOkHttpRequest(list, new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        ranage[0]++;
                        // Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String responseData = response.body().string();//得到服务器返回的具体内容
                        Log.d("MainActivity", "测试结果" + responseData);
                        if (responseData.startsWith("{")) {
                            Send();
                        } else {
                            count++;
                            parseJSONWithGSON(responseData, 19723756L);

                            Intent intent = new Intent(getActivity(), PlayActivity.class);
                            FindImgUrlPath = ssNew.getImageurl();//获取图片地址设置全局供ListFragment接收
                            FindSongsId = ssNew.getId();//获取FindFragment歌单ID

                            String ft = "推荐榜单";
                            EventBus.getDefault().postSticky(new MessageEvent(ft));//发送
                            getActivity().startActivity(intent);
//                            }
                        }

                    }
                });
            }
        });
        //收藏歌单
        linearLayoutMySong = view.findViewById(R.id.MySong);
        // 设置点击监听器
        linearLayoutMySong.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SuspiciousIndentation")
            @Override
            public void onClick(View v) {
                // 这里写您的点击事件处理代码
                count++;
                Intent intent = new Intent(getActivity(), PlayActivity.class);
                MyStarredSong = true;

                StarredSong song = helper.getFirstStarredSong();
                if (song != null)
                    FindImgUrlPath = song.getPic();
                String ft = "我的收藏";
                EventBus.getDefault().postSticky(new MessageEvent(ft));//发送
                Objects.requireNonNull(getActivity()).startActivity(intent);
            }
        });

        mzBanner.setPages(list, new MZHolderCreator<BannerViewHolder>() {
            @Override
            public BannerViewHolder createViewHolder() {
                return new BannerViewHolder();
            }
        });
    }


    public void initRvGird(View view) {
        rv_Grid = view.findViewById(R.id.rv_Grid);
        refreshLayout = view.findViewById(R.id.refresh_view);
        rv_Grid.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        rv_Grid.addItemDecoration(new GridSpaceitemDecoration(getResources().getDimensionPixelSize(R.dimen.dp_5), rv_Grid));
        rv_Grid.setFocusable(false);//获取焦点
        musicGridAdapter = new MusicGridAdapter(getActivity(), mDatas);
        rv_Grid.setAdapter(musicGridAdapter);
//        refreshLayout.setLoadMore(true);
        refreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {

            @Override

            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {

                mDatas.clear();
                sendRequestWithOkHttp();
                curState = STATE_REFRESH;
//                hotWareList.scrollToPosition(0);
                refreshLayout.finishRefresh();
            }


            @Override

            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {

            }

        });
    }

    public static int count = 0;
    public static int[] ranage = {6, 6};

    public void sendRequestWithOkHttp() {

        for (int i = 0; i < ranage[0]; i++) {
            //获取十个歌单
            Send();
        }
    }

    public void Send() {
        long randomLong = (long) (Math.random() * ((max - min) + 1)) + min; // 生成随机数
        String list = findsongs + randomLong;
        HttpUtil.sendOkHttpRequest(list, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ranage[0]++;
                // Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData = response.body().string();//得到服务器返回的具体内容
                Log.d("MainActivity", "测试结果" + responseData);
                if (responseData.startsWith("{")) {
                    Send();
                } else {
                    count++;
                    parseJSONWithGSON(responseData, randomLong);
//                            if (mDatas.size() == ranage[1]) {

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            musicGridAdapter.notifyDataSetChanged();
                        }
                    });
//                            }
                }

            }
        });

    }

    public HotSongs parseJSONWithGSON(String jsonData, Long randomLong) {

        try {
            JSONArray jsonArray = new JSONArray(jsonData);
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            String name = jsonObject.getString("name") + "系列";  //获取到json数据中的activity数组里的内容name
            String image = jsonObject.getString("pic");//获取歌单图片
            int playCount = jsonArray.length();//歌单播放数量
            long songsId = randomLong;//歌单id
            SongsDatas ss = new SongsDatas();
            ss.setTitle(name);
            ss.setImageurl(image);
            Random random = new Random();
            int number = 10 + random.nextInt(990) / 10 * 10;
            ss.setPlayCount(number + "");
            ss.setId(songsId);
            if (randomLong == 3778678L)
                ssHot = ss;
            else if (randomLong == 19723756L)
                ssNew = ss;
            else
                mDatas.add(ss);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "获取服务器数据失败", Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    @Override
    public void onPause() {
        super.onPause();
        mzBanner.pause();//暂停轮播
    }

    @Override
    public void onResume() {
        super.onResume();
        mzBanner.start();//开始轮播
    }
}